import { colorful, compare, isInArray } from "@/utils"
import { terminalData } from "../room/core/constant"

export default class terminalExtension extends StructureTerminal {
    /* 终端拓展 */
    public ManageMisson():void{
        if (!this.room.memory.Misson['Structure']) this.room.memory.Misson['Structure'] = []
        var allmyTask = []
        for (var task of this.room.memory.Misson['Structure'])
        {
            if (!task.structure) continue
            if (isInArray(task.structure,this.id))
            {
                allmyTask.push(task)
            }
        }
        /* 按照优先级排序 */
        if (allmyTask.length <= 0)
        {
            /* 没有任务就是默认情况下的处理函数 */
            this.StoreResource()
            this.MarketTerminal()
            return
        }
        else if (allmyTask.length >= 1)
            allmyTask.sort(compare('level'))
        /* 处理任务 */
        let thisTask = allmyTask[0]
        // if (this.room.name == 'E49S53') console.log(thisTask.name)
        /* 收纳资源任务需要及时处理 */
        if (thisTask.name != '资源传送')
        {
            this.StoreResource()
            this.MarketTerminal()
        }
        if (thisTask.delayTick < 99995)
            thisTask.delayTick--
        switch (thisTask.name){
            case "资源传送":{this.SendResource(thisTask);break}
            case "资源购买":{this.BuyResource(thisTask);break}
        }
    }
    /* 发送资源任务 */
    public SendResource(task:MissionModel):void{
        if (this.cooldown && this.cooldown > 0) return
        if (!task.data || !task.data.disRoom)
        {
            this.room.DeleteMisson(task.id)
            return
        }
        if (!task.data.state) task.data.state = 1   /* 状态1：资源校核准备期 */
        if (task.data.state == 1)
        {
            if (Game.time % 10) return  /* 每10tick监测一次 */
            if (task.data.num <= 0 || task.data.num == undefined) this.room.DeleteMisson(task.id)
            if (this.room.RoleMissonNum('manage','物流运输') > 0) return // manage爬虫有任务时就不管
            // 路费
            var wastage = Game.market.calcTransactionCost(task.data.num,this.room.name,task.data.disRoom)
            /* 如果非能量资源且路费不够，发布资源搬运任务，优先寻找storage */
            var storage_ = Game.getObjectById(this.room.memory.StructureIdData.storageID) as StructureStorage
            // terminal的剩余资源
            var remain = this.store.getFreeCapacity()
            console.log('终端剩余容量',remain)
            /* 路费判断 */
            if (wastage > this.store.getUsedCapacity('energy'))
            {
                /* 如果非能量资源且路费不够，发布资源搬运任务，优先寻找storage */
                var storage_ = Game.getObjectById(this.room.memory.StructureIdData.storageID) as StructureStorage
                /* 只有在能量富裕的情况下才会允许进入下一阶段 */
                if (storage_ && storage_.store.getUsedCapacity('energy') + this.store.getUsedCapacity('energy') - 5000 > wastage && remain > wastage-this.store.getUsedCapacity('energy'))
                {
                    /* 下布搬运任务 */
                    var thisTask = this.room.Public_Carry({'manage':{num:1,bind:[]}},40,this.room.name,storage_.pos.x,storage_.pos.y,this.room.name,this.pos.x,this.pos.y,'energy',wastage-this.store.getUsedCapacity('energy'))
                    this.room.AddMisson(thisTask)
                    return
                }
                /* 条件不满足就自动删除任务 */
                this.room.DeleteMisson(task.id)
                return
            }
            console.log('资源传送任务监控中: ###########################\n 房间：',this.room.name,'--->',task.data.disRoom,' 运送资源：',task.data.rType)
            console.log('路费:',colorful(`${wastage}`,'yellow'),'energy  ','终端拥有能量:',colorful(`${this.store.getUsedCapacity('energy')}`,'yellow'),'energy')
            /* 资源判断 */
            var cargoNum:number = task.data.rType == 'energy'?this.store.getUsedCapacity(task.data.rType)-wastage:this.store.getUsedCapacity(task.data.rType)
            console.log('终端拥有资源量:',colorful(`${cargoNum}`,'blue'),' 仓库拥有资源量:',storage_.store.getUsedCapacity(task.data.rType),' 任务所需资源量:',task.data.num)
            if (task.data.num > cargoNum)
            {
                if (storage_ && storage_.store.getUsedCapacity(task.data.rType) + this.store.getUsedCapacity(task.data.rType) >= task.data.num - 1600 && remain > task.data.num-cargoNum)
                {
                    /* 下布搬运任务 */
                    var thisTask = this.room.Public_Carry({'manage':{num:1,bind:[]}},40,this.room.name,storage_.pos.x,storage_.pos.y,this.room.name,this.pos.x,this.pos.y,task.data.rType,task.data.num-cargoNum)
                    this.room.AddMisson(thisTask)
                    return
                }
                /* 条件不满足就自动删除任务 */
                this.room.DeleteMisson(task.id)
                return
            }
            /* 都满足条件了就进入状态2 */
            task.data.state = 2
        }
        /* 状态2：资源传送监测期 */
        else if (task.data.state == 2)
        {
            /* 防止爬虫搬运过程中死亡导致的数据不匹配 */
            if (this.store.getUsedCapacity(task.data.rType) < task.data.num)
            {
                if (task.data.num - this.store.getUsedCapacity(task.data.rType) <= 1000)
                {
                    task.data.num -= (task.data.num - this.store.getUsedCapacity(task.data.rType))
                }
            }
            let result = this.send(task.data.rType as ResourceConstant,task.data.num as number,task.data.disRoom as string)
            if (result == -6)   /* 资源不够就重新返回状态1 */
            {
                task.data.state = 1
                return
            }
            else if (result == OK)
            {
                /* 如果传送成功，就删除任务 */
                this.room.DeleteMisson(task.id)
                return
            }
        }

    }
    /* 资源收纳任务 包括energy的自动挂单  默认状态 */
    public StoreResource():void{
        if (Game.time % 7 || this.room.controller.level < 6 ) return
        if (this.room.RoleMissonNum('manage','物流运输') > 0) return // manage爬虫有任务时就不管
        if (!this.room.memory.TerminalData) this.room.memory.TerminalData = terminalData
        var storage_ = Game.getObjectById(this.room.memory.StructureIdData.storageID) as StructureStorage
        if (!storage_)return
        /* 资源过于饱和就卖掉资源 */
        if (storage_.store.getFreeCapacity() < 50000)
        {
            /* 如果仓库饱和(小于200k空间)，而且仓库能量超过400K,就卖能量 */
            if (storage_.store.getFreeCapacity() < 200000 && storage_.store.getUsedCapacity('energy') > 400000)
            {
                if (!this.room.memory.market) this.room.memory.market = {}
                if (!this.room.memory.market['deal']) this.room.memory.market['deal'] = []
                var bR = true
                for (var od of this.room.memory.market['deal'])
                {
                    if (od.rType == 'energy')
                    bR = false
                }
                if (bR){
                    /* 下达自动deal的任务 */
                    this.room.memory.market['deal'].push({rType:'energy',num:100000})
                }
            }
        }
        var level = this.room.controller.level
        // 仓送终端
        for (var index in this.room.memory.TerminalData)
        {
            if (!this.room.memory.TerminalData[index].fill) continue
            /* 仓库能量太少就自助下单购买 满足条件：仓库中storage的能量少于100K并且仓库空闲大于40k */
            if (index == 'energy' && storage_.store.getUsedCapacity('energy') < 200000 && this.store.getFreeCapacity() > 50000 && storage_.store.getFreeCapacity()>=40000 && Game.market.credits > 1000000)
            {
                if (Game.time % 20) continue
                /* 查找市场上能量订单 */
                /* 计算平均价格 */
                let history = Game.market.getHistory('energy')
                let allprice = 0
                for (var ii=11;ii<14;ii++)
                    allprice += history[ii].avgPrice
                let avePrice = allprice/3 + 0.5 // 平均能量价格
                /* 清理过期订单 */
                if (Object.keys(Game.market.orders).length > 150)
                {
                    
                    for (let j in Game.market.orders)
                    {
                        let order = Game.market.getOrderById(j);
                        if (order.amount <=0 || !order.active) Game.market.cancelOrder(j);
                    }
                }
                console.log("订单操作中")
                /* 判断有无自己的订单 */
                let thisRoomOrder = Game.market.getAllOrders(order =>
                    order.type == ORDER_BUY && order.resourceType == 'energy' && order.price >= avePrice - 0.2 && order.roomName == this.room.name)
                /* 没有就创建订单 */
                if ((!thisRoomOrder || thisRoomOrder.length <= 0) && this.store.getUsedCapacity('energy') <= 60000)
                {
                    Game.market.createOrder({
                        type: ORDER_BUY,
                        resourceType: 'energy',
                        price: avePrice,
                        totalAmount: 100000,
                        roomName: this.room.name   
                    });
                    console.log(`房间${this.room.name}创建能量订单，价格:${avePrice};数量:100000`)
                }
                // const StaticavePrice = Game.market.getHistory('energy')[0]?Game.market.getHistory('energy')[0].avgPrice:1 as number
                // let priceAll = 0
                // var energyAllorders = Game.market.getAllOrders(order => order.type == ORDER_BUY && order.resourceType == 'energy' && order.price >StaticavePrice + 0.5 && order.price < 4)
                // for (var o of energyAllorders) priceAll += o.price
                // const avePrice = priceAll/energyAllorders.length 
                // this.room.MakeOrder('buy','energy',50000,avePrice)
                // console.log(avePrice)
            }
            /* 少了就补充 */
            if (this.store.getUsedCapacity(index as ResourceConstant) < this.room.memory.TerminalData[index].num)
            {
                var fill = this.room.memory.TerminalData[index].fill
                var DataLevel = this.room.memory.TerminalData[index].level
                if (fill && level>= DataLevel && storage_.store.getUsedCapacity(index as ResourceConstant) >= this.room.memory.TerminalData[index].num - this.store.getUsedCapacity(index as ResourceConstant) )
                {
                    var thisTask = this.room.Public_Carry({'manage':{num:1,bind:[]}},40,this.room.name,storage_.pos.x,storage_.pos.y,this.room.name,this.pos.x,this.pos.y,index as ResourceConstant,this.room.memory.TerminalData[index].num- this.store[index])
                    this.room.AddMisson(thisTask)
                    return
                }
            }
        }
        // 终端送仓
        for (var i in this.store)
        {
            if (!this.room.memory.TerminalData[i]) this.room.memory.TerminalData[i] = {num:0,level:8,fill:false}
            // 多余的部分就删除
            if (this.store[i] > this.room.memory.TerminalData[i].num)
            {
                
                var thisTask = this.room.Public_Carry({'manage':{num:1,bind:[]}},16,this.room.name,this.pos.x,this.pos.y,this.room.name,storage_.pos.x,storage_.pos.y,i as ResourceConstant,this.store.getUsedCapacity(i as ResourceConstant)-this.room.memory.TerminalData[i].num)
                this.room.AddMisson(thisTask)
                return
            }
        }
    }
    /* 购买资源任务 一次建议购买最多50k */
    public BuyResource(task:MissionModel):void{
        if(Game.time % 10) return
        if (this.cooldown && this.cooldown > 0 || this.store.getUsedCapacity('energy') < 50000) return
        if (!task.data)
        {
            this.room.DeleteMisson(task.id)
            return
        }
        var money = Game.market.credits
        if (money <= 0 || task.data.num > 60000){this.room.DeleteMisson;return}
        var rType = task.data.rType
        var num = task.data.num
        var HistoryList = Game.market.getHistory(rType)
        var allNum:number = 0
        for (var i of HistoryList)
        {
            allNum += i.avgPrice
        }
        var avePrice = allNum/HistoryList.length
        var maxPrice = avePrice + task.data.range
        /* 在市场上寻找 */
        var orders = Game.market.getAllOrders(order => order.resourceType == rType &&
            order.type == ORDER_SELL && order.price <= maxPrice)
        if (orders.length <= 0) return
        /* 寻找价格最低的 */
        var newOrderList = orders.sort(compare('price'))
        for (var ii of newOrderList)
        {
            if (ii.price > maxPrice) return
            if (ii.amount >= num)
            {
                if (Game.market.deal(ii.id,num,this.room.name) == OK)
                {
                    this.room.DeleteMisson(task.id)
                    return
                }
                else
                {
                    console.log(this.room.name,'deal交易发生错误')
                    return
                }
            }
            else
            {
                Game.market.deal(ii.id,ii.amount,this.room.name)
                task.data.num -= ii.amount
                return
            }
        }
    }
    /* 商业行为任务 自动deal买单 自动下单卖 */
    public MarketTerminal():void{
        if (Game.time % 20) return
        //if (this.room.name == 'E49S44') console.log('market')
        if (!this.room.memory.market) this.room.memory.market = {}
        LoopA:
        for (var r in this.room.memory.market)
        {
            if (r == 'deal')
            {
                if (this.store.getUsedCapacity('energy') < 50000) continue
                LoopB:
                for (var i of this.room.memory.market['deal'])
                {
                    if (i.rType != 'energy')
                    {
                        this.room.memory.TerminalData[i.rType] = {num:5000,level:6,fill:true}
                    }
                    /* 数量少了就删除 */
                    if (i.num <= 0)
                    {
                        if (i.rType != 'energy')
                        this.room.memory.TerminalData[i.rType] = {num:0,level:6,fill:false}
                        var index = this.room.memory.market['deal'].indexOf(i)
                        this.room.memory.market['deal'].splice(index,1)
                        continue LoopB
                    }
                    var orders = Game.market.getAllOrders(order => order.resourceType == i.rType &&
                        order.type == ORDER_BUY && order.amount >= 1000 && order.amount <= 30000)
                    if (orders.length <= 0) continue LoopB
                    /* 按价格从低到高排列 */
                    var newOrderList = orders.sort(compare('price'))
                    // 倒数第二
                    var thisDealOrder = newOrderList.length > 1?newOrderList[newOrderList.length - 2]:newOrderList[newOrderList.length - 1]
                    if (thisDealOrder.amount >= this.store.getUsedCapacity(i.rType))
                    {
                        Game.market.deal(thisDealOrder.id,this.store.getUsedCapacity(i.rType),this.room.name)
                        i.num -= this.store.getUsedCapacity(i.rType)
                        break LoopA
                    }
                    else
                    {
                        Game.market.deal(thisDealOrder.id,thisDealOrder.amount,this.room.name)
                        i.num -= thisDealOrder.amount
                        break LoopA
                    }
                }
            }
            else if (r == 'order')
            {
                /* 卖资源 */
                for (var i of this.room.memory.market['order'])
                {
                    /* 寻找订单 */
                    if (!i.id)
                    {
                        // if (this.store.getUsedCapacity(i.rType) < i.unit)
                        // {
                        //     this.room.memory.TerminalData[i.rType] = {num:i.unit,fill:true,level:this.room.controller.level}
                        //     return
                        // }
                        // /* 先寻找有没有与该房间有关的资源 */
                        // var orders = Game.market.getAllOrders(order => order.resourceType == i.rType &&
                        // order.type == ORDER_SELL && order.roomName == this.room.name)
                        // if (orders.length > 0) i.id = orders[0].id
                        // else
                        // {
                        //     console.log(this.room.name,"创建订单!",i.rType,' 价格：',i.price)
                        //     var result = Game.market.createOrder({
                        //     type: ORDER_SELL,
                        //     resourceType: i.rType,
                        //     price: i.price,
                        //     totalAmount: i.unit,
                        //     roomName: this.room.name   
                        //     })
                        //     if (result != OK) console.log(`房间${this.room.name} 创建无效订单${i.rType}`)
                        // }
                    }
                    else
                    {
                        //console.log('正在交易订单 ',i.rType)
                        /* 获取本交易订单的信息 */
                        // var thisOrder = Game.market.getOrderById(i.id) as Order
                        // if (!thisOrder) {console.log('删除无效订单！ id:',i.id,'  !');delete i.id}
                        // var price = thisOrder.price
                        // if (i.price != price) Game.market.changeOrderPrice(i.id,price)
                        // var storage_ = global.Stru[this.room.name]['storage']
                        // if(!storage_)return
                        // /* 自动填充 */
                        // this.room.memory.TerminalData[i.rType] = {num:i.unit,fill:true,level:this.room.controller.level}
                        // if (i.continue)
                        // {
                        //     if (!thisOrder.active && this.store.getUsedCapacity(i.rType) > 0)
                        //     {
                        //         console.log(i.rType,'的交易订单进行扩容!')
                        //         Game.market.extendOrder(i.id,i.unit)
                        //     }
                        // }
                        // else
                        // {
                        //     if (!thisOrder.active&& this.store.getUsedCapacity(i.rType) > 0)
                        //     {
                        //         var index = this.room.memory.market['order'].indexOf(i)
                        //         this.room.memory.market['order'].splice(index,1)
                        //     }
                        // }
                    }
                }
            }
        }
        
        
    }

}